package javase.ch05.tcp01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Desc 服务端
 * @Author chenmin
 * @Date 2025/11/3
 *
 * 需求3：服务端接收多条消息，服务端也可以发送多条消息；
 * 客户端可以发送多条消息，也可以接收多条消息；（一对一，阻塞的现象）
 *
 * ServerSocket 服务端套接字
 *    构造方法
 *    new ServerSocket(端口号);
 *    常用API方法
 *    public Socket accept() throws IOException  接收客户端
 * Socket 客户端套接字
 *    构造方法
 *    new Socket(IP地址 , 端口号);
 *    常用API方法
 *    1.public InputStream getInputStream() throws IOException   读消息
 *    2.public OutputStream getOutputStream() throws IOException 写消息
 */
public class TCPServer {

    public static void main(String[] args) {
        System.out.println("----------- TCPServer ------------");
        ServerSocket ss = null;
        Socket socket = null;
        BufferedReader br = null;
        PrintWriter out = null;
        try {
            //启动服务端
            ss = new ServerSocket(10086);
            //等待接入客户端
            socket = ss.accept();
            System.out.println("成功接入客户端：" + socket.getRemoteSocketAddress());

            Scanner sc = new Scanner(System.in);
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream());

            //读消息
            String string = null;
            while ((string=br.readLine())!=null){
                if(string.equals("exit")){
                    System.out.println(socket.getRemoteSocketAddress() + "下线了！");
                }else{
                    System.out.println(socket.getRemoteSocketAddress() +"说：" + string);
                }

                //写消息
                System.out.println("服务器说：");
                String str = sc.nextLine();
                if(str.equals("exit")){
                    break;
                }
                out.println(str);
                out.flush();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            if(out!=null){
                out.close();
            }
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(ss!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
